#!/usr/bin/env python
import os, sys
from twisted.internet import reactor
from twisted.python import log

def on_error(e):
    print e
    return None

def select(file_list=[], types=[]):
    """
    Returns the list of files that qualify the pattern
    file_list => list of files to be matched
    type => Type of file to be returned 
    """
    result = []
    for f in file_list:
        for t in types:
            if not f.upper().endswith(t.upper()):
                continue
            result.append(f)
    return result
            
def get_file_list(path):
    """
    Scan the entire directory structure @ path
    path => A directory to scan
    returns a generator object.
    """
    for t in os.walk(path, topdown=True, onerror=on_error, followlinks=False):
        yield [os.path.sep.join([t[0], fname]) for fname in t[2]]
        

def scan(search_path='.'):
    """
    Scan the given path for files and directory structure
    """
    for e in os.walk(top=search_path, topdown=True, 
                     onerror=on_error, followlinks=True):
        for directory in e[1]:
            yield scan(os.path.join([e[0], directory]))
            
def walk(start, file_types):
    """
    Recusrsively walk through the path and search for desired media files
    """
    result = []
    for tup in os.walk(top=start, topdown=True, 
                     onerror=on_error, followlinks=True):
        flist = select(tup[2], file_types)
        for item in flist:
            yield os.path.sep.join((tup[0], item))

def run():
    log.startLogging(file('scanning.log', 'w'))
    reactor.callInThread(collect_media, ['/'], ['jpg', 'kdc'])
    reactor.run()
    
        
if __name__ == '__main__':
    run()
